package com.example.teacher.linstener;

import com.example.common.constants.MqConstants;
import com.example.common.constants.TakeConstants;
import com.example.common.domain.Messages.Mgs;
import com.example.common.domain.dto.SignInDto;
import com.example.common.domain.dto.WorkDto;
import com.example.teacher.Service.AttendanceService;
import com.example.teacher.Service.HomeworkService;
import com.example.teacher.Service.HomeworkStudentService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.transaction.Transactional;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class TeacherNotificationListener {

    @Autowired
    private AttendanceService attendanceService;
    @Autowired
    private HomeworkService homeworkService;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private HomeworkStudentService homeworkStudentService;

    @RabbitListener(queues = MqConstants.QUEUE_SAVE)
    public void handleTeacherNotification(Mgs mgs) throws JsonProcessingException {
        System.out.println("教师收到通知: ");
        // 根据通知类型进行不同处理
        switch (mgs.getType()) {
            case TakeConstants.SIGN_IN:
                handleSignInNotification(mgs);
                break;
            case TakeConstants.HOMEWORK:
                handleAssignmentNotification(mgs);
                break;
            default:
                System.err.println("未知类型通知: " + mgs.getType());
        }
    }

    @Transactional
    public void handleSignInNotification(Mgs mgs) throws JsonProcessingException {
        System.out.println("教师端处理签到通知: " + mgs.getData());
        // 反序列化为SignInDto
        SignInDto signInDto = (SignInDto) mgs.getData();
//        SignInDto signInDto = objectMapper.readValue((String) mgs.getData(), SignInDto.class);
        // 1. 存储通知到数据库
        attendanceService.saveAttendance(signInDto);
    }

    @Transactional
    public void handleAssignmentNotification(Mgs mgs) throws JsonProcessingException {
        System.out.println("教师端处理作业通知: " + mgs.getData());
        WorkDto workDt = (WorkDto) mgs.getData();
        System.out.println("Test:作业名字：" + workDt.getHomeworkName());
        // 1. 存储通知到数据库
        homeworkService.saveHomework(workDt);

    }
}
